package com.cctv.portal.sms.adapter;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public final class HttpClientUtil {
	
	private static final int socketTimeout = 3000;
	
	private static final int connectTimeout = 3000;
	
	private HttpClientUtil(){}
	
	public static String executeRequest(String uri,final String charset)throws ClientProtocolException, IOException {
		String responseBody = "";
		CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
	        HttpGet httpget = new HttpGet(uri);
//            HttpGet httpget = new HttpGet(uri);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();
            httpget.setConfig(requestConfig);
//            System.out.println("executing request:" + httpget.getURI());
            // Create a custom response handler
            ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
                public String handleResponse(
                        final HttpResponse response) throws ClientProtocolException, IOException {
                    int status = response.getStatusLine().getStatusCode();
                    if (status >= 200 && status < 300) {
                        HttpEntity entity = response.getEntity();
                        return entity != null ? EntityUtils.toString(entity, charset) : null;
                    } else {
                        throw new ClientProtocolException("Unexpected response status: " + status);
                    }
                }
            };
            responseBody = httpclient.execute(httpget, responseHandler);
//            System.out.println("----------------------------------------");
//            System.out.println(responseBody);
//            System.out.println("----------------------------------------");
        } finally {
            httpclient.close();
        }
		return responseBody;
	}
	
	public static String executeRequest(String uri) throws ClientProtocolException, IOException {
		return executeRequest(uri, "UTF-8");
	}
}
